package com.universal.common.utils;

import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author: austin
 * @since: 2023/1/6 15:31
 */
public class ObjectUtils extends org.apache.commons.lang3.ObjectUtils {

    public ObjectUtils() {
    }

    public static void annotationToObject(Object annotation, Object object) {
        if (annotation != null) {
            Class<?> annotationClass = annotation.getClass();
            Class<?> objectClass = object.getClass();
            Method[] var4 = objectClass.getMethods();
            int var5 = var4.length;

            for(int var6 = 0; var6 < var5; ++var6) {
                Method m = var4[var6];
                if (StringUtils.startsWith(m.getName(), "set")) {
                    try {
                        String s = StringUtils.uncapitalize(StringUtils.substring(m.getName(), 3));
                        Object obj = annotationClass.getMethod(s).invoke(annotation);
                        if (obj != null && !"".equals(obj.toString())) {
                            if (object == null) {
                                object = objectClass.newInstance();
                            }

                            m.invoke(object, obj);
                        }
                    } catch (Exception var10) {
                    }
                }
            }
        }

    }

    public static byte[] serialize(Object object) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;

        try {
            if (object != null) {
                baos = new ByteArrayOutputStream();
                oos = new ObjectOutputStream(baos);
                oos.writeObject(object);
                return baos.toByteArray();
            }
        } catch (Exception var4) {
            var4.printStackTrace();
        }

        return null;
    }

    public static Object unserialize(byte[] bytes) {
        ByteArrayInputStream bais = null;

        try {
            if (bytes != null && bytes.length > 0) {
                bais = new ByteArrayInputStream(bytes);
                ObjectInputStream ois = new ObjectInputStream(bais);
                return ois.readObject();
            }
        } catch (Exception var3) {
            var3.printStackTrace();
        }

        return null;
    }

    public boolean checkObjectFieldIsNull(Object obj) throws IllegalAccessException {
        boolean flag = false;
        Field[] var3 = obj.getClass().getDeclaredFields();
        int var4 = var3.length;

        for(int var5 = 0; var5 < var4; ++var5) {
            Field f = var3[var5];
            f.setAccessible(true);
            if (f.get(obj) == null) {
                flag = true;
                return flag;
            }
        }

        return flag;
    }
}
